import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useState } from 'react';
import { useAppSelector } from '@/store';
import { useDispatch } from 'react-redux';
import {
  getCommentsByIdAction,
  getReplyCommentsByIdAction,
  submitCommentAction,
} from '@/store/action/common';
type Props = {
  // 评论的作者的名字
  name?: string;
  onBack: () => void;
};
export default function CommentInput({ name, onBack }: Props) {
  const [value, setValue] = useState('');
  const { originComment } = useAppSelector((state) => state.comment);
  const { detail } = useAppSelector((state) => state.article);
  const dispatch = useDispatch();
  const handleSubmit = async () => {
    // 1. 逻辑判断，如果存在原始数据的comm_id表示对回复评论
    if (originComment.com_id) {
      await dispatch(
        submitCommentAction({ target: originComment.com_id, content: value, art_id: detail.art_id })
      );

      // 3. 使用获取回复列表的action，刷新请求
      dispatch(getReplyCommentsByIdAction(originComment.com_id));
      // 4. 提示成关闭界面
      Toast.show({ content: '发表成功' });
      onBack();
      return;
    }
    // 2. 如果不存在com_id，代表对文章评论
    await dispatch(submitCommentAction({ target: detail.art_id, content: value }));
    Toast.show({ content: '发布成功' });
    dispatch(getCommentsByIdAction({ type: 'a', source: detail.art_id }));
    onBack();
  };
  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="publish" onClick={handleSubmit}>
            发表
          </span>
        }
        onBack={onBack}
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {/* 回复别人的评论时显示：@某某 */}
        {name && <div className="at">@{name}:</div>}

        {/* 评论内容输入框 */}
        <TextArea
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(stringVal) => {
            setValue(stringVal);
          }}
        />
      </div>
    </div>
  );
}
